#include "../../Base/StdAfx.h"
#include "../../Base/GameEngine.h"
#include "../../Base/DXDevice.h"
#include "Quad.h"
#include "../../Base/vertex.h"
#include "../../Effects/Effect.h"
#include "../../Base/DirectInput.h"

void Quad::Draw()
{
	GETDEVICE->IASetInputLayout(m_VertexLayoutPtr);
	UINT stride = sizeof(VertexPT);
	UINT offset = 0;
	m_Effect->SetTexture(m_Texture);
	GETDEVICE->IASetVertexBuffers(0, 1, &m_VertexBufferPtr, &stride, &offset);
	GETDEVICE->IASetIndexBuffer(m_IndexBuffer, DXGI_FORMAT_R32_UINT, 0);
	GETDEVICE->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	D3D10_TECHNIQUE_DESC tech;
	m_Effect->GetTech()->GetDesc( &tech);
	for(UINT t = 0; t < tech.Passes; ++t)
	{
		m_Effect->GetTech()->GetPassByIndex(t)->Apply(0);
		GETDEVICE->DrawIndexed(6, 0, 0);
	}
}

void Quad::Init()
{
	m_Armed = false;

	vector<VertexPT> v;
	v.push_back(VertexPT(-1, 1, 0.9f, 0, 0));
	v.push_back(VertexPT(1, 1, 0.9f, 1, 0));
	v.push_back(VertexPT(1, -1, 0.9f, 1, 1));
	v.push_back(VertexPT(-1, -1, 0.9f, 0, 1));

	vector<DWORD> i;
	i.push_back(0);i.push_back(1);i.push_back(2);
	i.push_back(0);i.push_back(2);i.push_back(3);

	D3D10_BUFFER_DESC bdesc;
	bdesc.Usage = D3D10_USAGE_DEFAULT;
	bdesc.ByteWidth = sizeof(VertexPT) * 4;
	bdesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
	bdesc.CPUAccessFlags = 0;
	bdesc.MiscFlags = 0;
	D3D10_SUBRESOURCE_DATA subdesc;
	subdesc.pSysMem = &v[0];
	DXDevice::GetSingleton()->GetDevice()->CreateBuffer(&bdesc, &subdesc, &m_VertexBufferPtr);
	
	D3D10_BUFFER_DESC idesc;
	idesc.Usage = D3D10_USAGE_DEFAULT;
	idesc.ByteWidth = sizeof(DWORD) * 6;
	idesc.BindFlags = D3D10_BIND_INDEX_BUFFER;
	idesc.CPUAccessFlags = 0;
	idesc.MiscFlags = 0;
	D3D10_SUBRESOURCE_DATA subidesc;
	subidesc.pSysMem = &i[0];
	DXDevice::GetSingleton()->GetDevice()->CreateBuffer(&idesc, &subidesc, &m_IndexBuffer);

	m_Effect = new Effect(_T("./Shaders/Blur.fx"));

	D3D10_INPUT_ELEMENT_DESC layout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
	};
	UINT numElements = sizeof( layout ) / sizeof( layout[0] );

	// Create the input layout
	D3D10_PASS_DESC PassDesc;
	m_Effect->GetTech()->GetPassByIndex( 0 )->GetDesc( &PassDesc );
	DXDevice::GetSingleton()->GetDevice()->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_VertexLayoutPtr );

}

Quad::Quad( const D3DXVECTOR3& pos)
{
	m_Pos = pos;
	Init();
}

Quad::~Quad()
{
	delete m_Effect;
	m_VertexBufferPtr->Release();
	m_IndexBuffer->Release();
	m_VertexLayoutPtr->Release();
}

void Quad::SetTexture( const ID3D10ShaderResourceView* tex )
{
	m_Texture = const_cast<ID3D10ShaderResourceView*>(tex);
}